<?php
	/**
	 * 
	 * @param unknown_type $pMerBillNo
	 * @return string
	 */


	
	/**
	 * 投标
	 * @param int $user_id  用户ID
	 * @param int $deal_id  标的ID
	 * @param float $pAuthAmt 投资金额
	 * @param int $MerCode  商户ID
	 * @param string $cert_md5 
	 * @param string $post_url
	 * @return string
	 */

	//function RegisterCreditor($user_id,$deal_id,$pAuthAmt,$platformNo,$post_url){
	function RegisterCreditor($user_id,$deal_id,$pAuthAmt,$ecv_id = 0,$interestrate_id=0,$use_interestrate=0,$platformNo,$post_url){
		
		set_time_limit(0);
		$pWebUrl= SITE_DOMAIN."/index.php?m=Home&c=collocation&a=response_go&class_name=".COLLNAME."&class_act=RegisterCreditor&from=wap" ;//web方式返回
		$pS2SUrl= SITE_DOMAIN."/index.php?m=Home&c=collocation&a=notify&class_name=".COLLNAME."&class_act=RegisterCreditor&from=wap" ;//s2s方式返回
			
		$deal = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."deal where id = ".$deal_id);
		
		$user = get_user_info("*","id = ".$deal['user_id']);
		$tuser = get_user_info("*","id = ".$user_id);

		if (empty($user['ips_acct_no']) || empty($tuser['ips_acct_no'])){
			$result = array();
			$result['status'] = 0;
			$result['message'] = '有一方未申请 ips 帐户';
			return $result;
			edit();;
		}
		
		/*if((!$GLOBALS['user_info'] && !$GLOBALS['t_user_info']) || ($GLOBALS['user_info']['id']!=$user_id && $GLOBALS['t_user_info']['id']!=$user_id)){
			if($_REQUEST['from']=="wap"){
				showIpsInfo("投资失败",SITE_DOMAIN.wap_url('index',"deal",array("id"=>$deal_id)));
			}
			else{
				showIpsInfo("投资失败",SITE_DOMAIN.url('index',"deal#index",array("id"=>$deal_id)));
			}
			edit();
		}*/
		
		
		/*$GLOBALS['db']->query("UPDATE ".DB_PREFIX."user set bid_lock = 1,bid_lock_time=".TIME_UTC." WHERE id=".$user_id." AND (bid_lock =0 OR (bid_lock = 1 AND bid_lock_time <".(TIME_UTC-10).") ) ");
		if(!$GLOBALS['db']->affected_rows()){
			
			$result = array();
			$result['status'] = 0;
			$result['message'] = '您已完成投资,请稍后';
			return $result;
			edit();;
		}*/

		$GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal set ips_money = ips_money + ".$pAuthAmt." WHERE id=".$deal_id." and ips_money + ".$pAuthAmt." <= borrow_amount ");

        $rs = M('deal')->where( "id=".$deal_id  )->find();
        if( empty($rs['ips_money'])){
            $ips_money_old = 0 ;
        }else{
            $ips_money_old = $rs['ips_money'] ;
        }
        //$data1['ips_money'] = $ips_money_old + $pAuthAmt ;
        //$affect = M('deal')->where( "id=".$deal_id." and ips_money + ".$pAuthAmt." <= borrow_amount" )->save($data1);
        //echo  M('deal')->getlastsql();
        //"UPDATE ".DB_PREFIX."deal set ips_money = ips_money + ".$pAuthAmt." WHERE id=".$deal_id." and ips_money + ".$pAuthAmt." <= borrow_amount "
 		if(false){

			$ips_money = $GLOBALS['db']->getOne("SELECT sum(money) FROM ".DB_PREFIX."deal_load where deal_id=".(int)$deal_id);
			$GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal set ips_money =  ".$ips_money." WHERE id=".(int)$deal_id." ");	
			
			$result = array();
			$result['status'] = 0;
			$result['message'] = '投资失败';
			return $result;
			edit();;
		}

		$fuioupay_log = array();
		$fuioupay_log['code'] = 'toCpTransaction';
		$fuioupay_log['create_date'] = to_date(TIME_UTC,'Y-m-d H:i:s');
		$GLOBALS['db']->autoExecute(DB_PREFIX."fuioupay_log",$fuioupay_log);
		$requestNo = $GLOBALS['db']->insert_id();
		$data = $Sign_data= array();
		$data['requestNo'] = $requestNo;//请求流水号
		$data['platformUserNo'] = $user_id;//
		
		
		$Sign_data['mchnt_cd'] = $platformNo;// 商户编号
		$data['mchnt_txn_ssn'] = $Sign_data['mchnt_txn_ssn'] = $user_id.get_microtime();



		$data['interestrate_id'] = 0;
		if(intval($interestrate_id) > 0 && intval($use_interestrate > 0)){
			//获得加息券的金额
			$ecv_info = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."interestrate where id = ".intval($interestrate_id)." AND (begin_time =0 OR (begin_time > 0 AND begin_time < ".TIME_UTC.")) AND (end_time = 0 OR (end_time > 0  AND (end_time +24*3600 - 1) > ".TIME_UTC.")) AND (use_limit =0  OR (use_limit >0 AND use_limit - use_count > 0)) AND ((user_id=".$user_id." and to_user_id =0 ) or to_user_id =".$user_id.")");

			if($ecv_info){
				$data['interestrate_id'] = $ecv_info['id'];
				$ecv_id = 0;
			}
			
		}
		//echo 'ecv_id:'.$ecv_id;
		$data['ecv_id'] = 0;
		if(intval($use_interestrate) == 0){
            //echo 1234;
            //echo '$ecv_id'.$ecv_id;
			if(intval($ecv_id) > 0){
				//获得红包的金额

				$ecv_info = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."ecv where id = ".intval($ecv_id)."  AND user_id=".$user_id);
                if($ecv_info){
					$data['ecv_id'] = $ecv_info['id'];
					/*
					if($pAuthAmt < $ecv_info['money'])
					{
						$ecv_info['money'] = $pAuthAmt;
					}*/
                    if(empty($ecv_info['money'])){
                        $ecv_info['money'] = 0;
                    }
                    $pAuthAmt = $pAuthAmt - $ecv_info['money'];
					//echo '红包金额是'.$ecv_info['money'];
				}
				
			}
		}
        //echo '支付金额是'.$pAuthAmt;
//exit;
		$Sign_data['amt'] = $pAuthAmt*100;// 记录投标金额
		
		$Sign_data['ver'] = "0.44";
		
		$data['rem'] = $Sign_data['rem'] ='预冻结';
		
		
		$data['out_cust_no'] =$Sign_data['out_cust_no'] = $tuser['mobile'];// 付款登录账户
		$data['in_cust_no'] =$Sign_data['in_cust_no'] =$user['mobile'];// 收款登录账户
		
		
		ksort($Sign_data);
		foreach($Sign_data as $k => $v){
			if($k == 'ver'){
				$Sign_old .=$v;
				$Sign_old_a .=$k;
			}else{
				$Sign_old .=$v."|";
				$Sign_old_a .=$k."+|+";
			}
		}

		$pSign=rsaSign($Sign_old,PRIVATE_KEY_PATH);

		//用户类型 0普通用户 1 企业用户；现在只支持 普通用户
		if (true){
			$data['userType'] = 'MEMBER';//出款人用户类型
		}else{
			$data['userType'] = 'MERCHANT';//出款人用户类型MEMBER 个人会员 MERCHANT 商户 
		}
		
		//TENDER 投标 REPAYMENT 还款 CREDIT_ASSIGNMENT 债权转让 TRANSFER 转账 COMMISSION 分润，仅在资金转账明细中使用
		$data['bizType'] = 'TENDER';//根据业务的不同，需要传入不同的值，见【业务类型】。并参考下面的详细信息
		
		//投标 扩展字段
		$data['tenderOrderNo'] = $deal_id;//订单编号
		$data['tenderName'] = $deal['name'];//项目名称 
		$data['tenderId'] = $deal['id'];//项目编号
		$data['tenderAmount'] = $deal['borrow_amount'];//标的金额
 		$data['paymentAmount'] = $pAuthAmt;//实际支付金额
		$data['tenderDescription'] = $deal['name'];//项目描述信息
		$data['borrowerPlatformUserNo'] = $deal['user_id'];//项目的借款人平台用户编号		  
		
 		if (true){
			$targetUserType = 'MEMBER';//出款人用户类型
		}else{
			$targetUserType = 'MERCHANT';//出款人用户类型MEMBER 个人会员  商户
		}
		
		//成交服务费

		//$data['fee'] =$fee; 
		//$data['fee'] = 0.00;
		//分红
		//$data['share_fee'] =$share_fee;
		//$data['share_fee'] =0.00;
		
		//$data['delivery_fee'] =$order['delivery_fee'];
		//$data['delivery_fee'] = '';
		//实际可到账金额
		if(true){
			$targetAmount = $pAuthAmt;
		}else{
			$targetAmount = $pAuthAmt - $fee-$share_fee;
		}
		
		$data['targetAmount'] =$targetAmount;
		$details = "<details><detail><targetUserType>".$targetUserType."</targetUserType><targetPlatformUserNo>".intval($deal['user_id'])."</targetPlatformUserNo><amount>".$targetAmount."</amount><bizType>TENDER</bizType></detail>"  
				  ."<detail><targetUserType>MERCHANT</targetUserType><targetPlatformUserNo>$platformNo</targetPlatformUserNo><amount>$fee</amount><bizType>COMMISSION</bizType></detail></details>";
		if($share_fee>0){
				$details.= "<detail><targetUserType>".$data['userType']."</targetUserType><targetPlatformUserNo>".$user_id."</targetPlatformUserNo><amount>$share_fee</amount><bizType>COMMISSION</bizType></detail>";
		}
				
		$extend = '<extend>'
				.'<property name="tenderOrderNo" value="'.$data['tenderOrderNo'].'" />'
				.'<property name="tenderName" value="'.$data['tenderName'].'" />'
				.'<property name="tenderAmount" value="'.$data['tenderAmount'].'" />'
				.'<property name="tenderDescription" value="'.$data['tenderDescription'].'" />'
				.'<property name="borrowerPlatformUserNo" value="'.$deal["user_id"].'" />'
				.'</extend>';		
		
		$data['details'] = $details;//资金明细记录
		$data['extend'] = $extend;//业务扩展属性，根据业务类型的不同，需要传入不同的参数
		$data['create_time'] = TIME_UTC;
        $id = M('fuioupay_cp_transaction')->add($data);
		//$GLOBALS['db']->autoExecute(DB_PREFIX."fuioupay_cp_transaction",$data,'INSERT');
		//$id = $GLOBALS['db']->insert_id();

		$req = http_build_query($Sign_data)."&signature=".urlencode($pSign);
		

		$options = array(
			CURLOPT_POST => TRUE,
			CURLOPT_RETURNTRANSFER => TRUE,
			CURLOPT_SSL_VERIFYPEER=>0,
			CURLOPT_SSL_VERIFYHOST=>0,
			CURLOPT_POSTFIELDS =>$req,
		
		);

	    $ch = curl_init($post_url); 
	    curl_setopt_array($ch,$options); 
	   	$resultStr = curl_exec($ch);
	    curl_close($ch); 
		//file_put_contents(APP_ROOT_PATH.'system/collocation/fuioupay/resul'.$id.'.php',$resultStr);

		if(empty($resultStr)){
			$result = array();
			$result['pErrCode'] = 9999;
			$result['pErrMsg'] = '返回出错';
		}else{
			require_once APP_ROOT_PATH.'system/collocation/fuioupay/xml.php';
			$str3ParaInfo = @XML_unserialize($resultStr);
			$str3Req = $str3ParaInfo['ap']['plain'];
			$result = array();
			$result['resp_code'] = $str3Req["resp_code"];
			$result['mchnt_cd'] = $str3Req["mchnt_cd"];
			$result['mchnt_txn_ssn'] = $str3Req["mchnt_txn_ssn"];
			$result['contract_no'] =  $str3Req['contract_no'];
			$result['signature'] =  $str3ParaInfo['ap']['signature'];
			$result['rsaXML'] = substr($resultStr,42,169);
			
		}
		$result['class_act'] = 'RegisterCreditor';
		$fuioupay_log = array();
		$fuioupay_log['html'] = $req;
		$fuioupay_log['strxml'] = $resultStr;
		$GLOBALS['db']->autoExecute(DB_PREFIX."fuioupay_log",$fuioupay_log,'UPDATE','id='.$requestNo);
		return $result;
	}

	//投资回调
	function RegisterCreditorCallBack($str3Req){
		
		$mchnt_txn_ssn = $str3Req["mchnt_txn_ssn"];
		if($mchnt_txn_ssn){
			unset($str3Req["mchnt_txn_ssn"]);
		}
		$str3Req['status'] = 1;
		$where = " mchnt_txn_ssn = '".$mchnt_txn_ssn."'";
		$ipsdata = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."fuioupay_cp_transaction where ".$where);

		if ($str3Req['resp_code'] == '0000'){

			//操作成功
			if (true){
 				$deal = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."deal where id = ".(int)$ipsdata['tenderOrderNo']);
				
				$user_id = intval($ipsdata['platformUserNo']);
				$user = get_user_info("*","id = ".$user_id);
				
				$GLOBALS['db']->query("UPDATE ".DB_PREFIX."user set bid_lock = 0 WHERE id=".$user_id);
				
				$requestNo = $ipsdata['requestNo'];
				$data['pMerBillNo'] = $requestNo;
				$data['pContractNo'] = $requestNo;
				$data['pP2PBillNo'] = $requestNo;
				$data['user_id'] = $user_id;
				$data['user_name'] = $user['user_name'];
				$data['deal_id'] = $ipsdata['tenderOrderNo'];
				$data['money'] = $ipsdata['paymentAmount'];
				$data['ecv_id'] = 0;
				
				$data['is_auto'] = intval($str3Req['is_auto']);
				
				if($ipsdata['ecv_id'] > 0){
					$GLOBALS['db']->query("UPDATE ".DB_PREFIX."ecv SET use_count = use_count + 1 WHERE (begin_time =0 OR (begin_time > 0 AND begin_time < ".TIME_UTC.")) AND (end_time = 0 OR (end_time > 0  AND (end_time +24*3600 - 1) > ".TIME_UTC.")) AND (use_limit =0  OR (use_limit >0 AND use_limit - use_count > 0)) AND id=".$ipsdata['ecv_id']." AND user_id=".$user_id);
					if($GLOBALS['db']->affected_rows()){
						$ecv_money = $GLOBALS['db']->getOne("SELECT `money` FROM ".DB_PREFIX."ecv WHERE id=".$ipsdata['ecv_id']);
						$data['money'] +=$ecv_money;
						$data['ecv_id'] = $ipsdata['ecv_id'];
					}
				}
				$data['interestrate_id'] = 0;
				$data['interestrate_money'] =0;
				if($ipsdata['interestrate_id'] > 0){
					$GLOBALS['db']->query("UPDATE ".DB_PREFIX."interestrate SET use_count = use_count + 1 WHERE (begin_time =0 OR (begin_time > 0 AND begin_time < ".TIME_UTC.")) AND (end_time = 0 OR (end_time > 0  AND (end_time +24*3600 - 1) > ".TIME_UTC.")) AND (use_limit =0  OR (use_limit >0 AND use_limit - use_count > 0)) AND id=".$ipsdata['interestrate_id']." AND ((user_id=".$user_id." and to_user_id =0 ) or to_user_id =".$user_id.")");
					//print_r("UPDATE ".DB_PREFIX."interestrate SET use_count = use_count + 1 WHERE (begin_time =0 OR (begin_time > 0 AND begin_time < ".TIME_UTC.")) AND (end_time = 0 OR (end_time > 0  AND (end_time +24*3600 - 1) > ".TIME_UTC.")) AND (use_limit =0  OR (use_limit >0 AND use_limit - use_count > 0)) AND id=".$ipsdata['interestrate_id']." AND ((user_id=".$user_id." and to_user_id =0 ) or to_user_id =".$user_id.")");die;
					if(true){
						$interestrate_money = $GLOBALS['db']->getOne("SELECT `rate` FROM ".DB_PREFIX."interestrate WHERE id=".$ipsdata['interestrate_id']);
						$data['interestrate_money'] =$interestrate_money;
						$data['interestrate_id'] = $ipsdata['interestrate_id'];
					}
				}
                $load_id = $return_deal_load_id = 0;
				$insertdata = return_deal_load_data($data,$user,$deal);
                $return_deal_load_id = M('deal_load')->add($insertdata);

                $sql = "update ".DB_PREFIX."fuioupay_cp_transaction set is_callback = 1,code='".$str3Req['resp_code']."',contract_no='".$str3Req['contract_no']."', deal_load_id = ".intval($return_deal_load_id)." where is_callback = 0 and ".$where;
                $GLOBALS['db']->query($sql);

                if($return_deal_load_id){
                    //添加到fanwe_fuioupay_cp_transaction_detail表
                    $insertDetailData['deal_load_id'] = $return_deal_load_id ;
                    $insertDetailData['user_id'] = $user_id ;
                    //暂时不存
                }
				//$GLOBALS['db']->autoExecute(DB_PREFIX."deal_load",$insertdata,"INSERT");
				$load_id = $return_deal_load_id;
				if($load_id > 0){
					if($ipsdata['ecv_id'] > 0)
						$GLOBALS['db']->query("UPDATE ".DB_PREFIX."ecv set use_id = ".$load_id." WHERE id=".$ipsdata['ecv_id']);
					if($ipsdata['interestrate_id'] > 0)
						$GLOBALS['db']->query("UPDATE ".DB_PREFIX."interestrate set use_id = ".$load_id." WHERE id=".$ipsdata['interestrate_id']);

					require_once APP_ROOT_PATH.'system/deal_func.php';
					//判断是否超出
					$total_money = $GLOBALS['db']->getOne("select sum(money) from ".DB_PREFIX."deal_load where deal_id =".(int)$ipsdata['tenderOrderNo']." and id <=".$load_id);
					
					$deal = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."deal where id = ".(int)$ipsdata['tenderOrderNo']);
					if($total_money > $deal['borrow_amount'])
					{
						require_once APP_ROOT_PATH."system/collocation/Fuioupay_collocation.php";
						$collocation_object = new Fuioupay_collocation();
						$collocation_code = $collocation_object->DoBidsOne($load_id);
						
						$str3Req['status'] = 0;
						$str3Req['message'] = '投标失败，撤标成功';
						return $str3Req;
					}
					else
					{
						dobid2_ok($ipsdata['tenderOrderNo'], $user_id);		
					}
				}
	  		}else{
				if (isset($str3Req['message'])){
					$str3Req['status'] = 0;
					$str3Req['message'] = '更新is_callback=1失败';
				}
	 		}
	 		//$GLOBALS['db']->autoExecute(DB_PREFIX."fuioupay_cp_transaction",$str3Req,'UPDATE',$where);
	 		$ips_money = $GLOBALS['db']->getOne("SELECT sum(money) FROM ".DB_PREFIX."deal_load where deal_id=".(int)$ipsdata['tenderOrderNo']);
			$GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal set ips_money =  ".$ips_money." WHERE id=".(int)$ipsdata['tenderOrderNo']." ");
	 		return $str3Req;
		}else{
			$ips_money = $GLOBALS['db']->getOne("SELECT sum(money) FROM ".DB_PREFIX."deal_load where deal_id=".(int)$ipsdata['tenderOrderNo']);
			$GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal set ips_money =  ".$ips_money." WHERE id=".(int)$ipsdata['tenderOrderNo']." ");	
 			return $str3Req;
		}
		
		
		
	}	
	
?>